const Koa = require("koa");
const mongoose = require("mongoose");
const config = require("./config");
const unit = require("./lib/unit");
const openBrowser = require("child_process");
const bodyParser = require("koa-bodyparser");
const rest = require("./rest_api");
const cors = require("koa2-cors");
const router_fn = require("./routers/index");
const globalFn = require("./lib/globalFn");
const adminInit = require('./addAdmin');
const serve = require("koa-static");
globalFn();

const app = new Koa();

app.use(serve(__dirname+ "/www"));

app.use(async (ctx, next) => {
  await next();
});



app.use(cors()); // 跨域
app.use(bodyParser()); // post参数获取
app.use(rest.restify()); // restAPI
app.use(router_fn()); //注册路由


// 链接数据库
mongoose.connect(config.databaseurl);
const db = mongoose.connection;
db.on('error',function(error){
	console.log('链接数据库失败：',error);
})
db.on('open',function(){
	console.log('链接数据库成功');
})
// 添加初始超级管理员
adminInit();


app.listen(3001);


// 打开浏览器
console.log("服务已启动...\nhttp://" + unit.getIp() + ":3001");
// openBrowser.exec('start http://'+ unit.getIp() + ':3001');
